Given a binary search tree with non-negative values, find the minimumabsolute differencebetween values of any two nodes.

Example:

Input:


   1
    \
     3
    /
   2


Output:

1


Explanation:

The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).

Note:There are at least two nodes in this BST.

/**

* Definition for a binary tree node.

* struct TreeNode {

* int val;

* TreeNode *left;

* TreeNode *right;

* TreeNode(int x) : val(x), left(NULL), right(NULL) {}

* };

*/

class Solution {

int result=2147483647;

    int val=-1;

public:

int getMinimumDifference\(TreeNode\* root\) {

    /\*if \(root==NULL\){ 

        return result;

    }

    if \(\(root->left==NULL\)&&\(root->right==NULL\)\) {

        return result;

    }



    if\(\(root->left!=NULL\)&&\(root->right!=NULL\)\){

        result=min\(root->val - root->left->val,root->right->val - root->val\);

        result=min\(result,getMinimumDifference\(root->left\)\);

        result=min\(result,getMinimumDifference\(root->right\)\);

    }

    else if\(\(root->left==NULL\)&&\(root->right!=NULL\)\){

        result=min\(root->right->val-root->val,getMinimumDifference\(root->right\)\);

    }

    else{

        result=min\(root->val - root->left->val,getMinimumDifference\(root->left\)\);

    }\*/

    if \(root->left != NULL\) getMinimumDifference\(root->left\);

    if \(val >= 0\) result = min\(result, root->val - val\);

    val = root->val;

    if \(root->right != NULL\) getMinimumDifference\(root->right\);

    return result;





}

};

这个全局变量设得妙啊

results matching ""

    No results matching ""